#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <ctype.h>
#include <pthread.h>
#include <arpa/inet.h>  // 包含inet_ntoa函数

#define PORT 8080
#define BUFFER_SIZE 1024

// 线程参数结构体
struct thread_args {
    int client_socket;
    struct sockaddr_in client_addr;
};

// 线程处理函数
void* client_handler(void* arg) {
    struct thread_args *args = (struct thread_args *)arg;
    int client_socket = args->client_socket;
    struct sockaddr_in client_addr = args->client_addr;
    free(arg);  // 立即释放参数内存

    // 输出客户端信息
    char client_ip[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, INET_ADDRSTRLEN);
    int client_port = ntohs(client_addr.sin_port);
    printf("Connected to client: %s:%d\n", client_ip, client_port);

    char buffer[BUFFER_SIZE] = {0};
    
    // 持续处理客户端通信
    while(1) {
        // 接收数据
        int valread = read(client_socket, buffer, BUFFER_SIZE - 1);
        if (valread <= 0) break;

        // 转换为大写
        for(int i = 0; i < valread; i++) {
            buffer[i] = toupper(buffer[i]);
        }

        // 发送响应
        send(client_socket, buffer, valread, 0);
        memset(buffer, 0, BUFFER_SIZE);  // 清空缓冲区
    }

    close(client_socket);
    pthread_exit(NULL);
}

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    
    // 1. 创建socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 2. 设置套接字选项
    int opt = 1;
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }

    // 3. 绑定地址
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);
    
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 4. 开始监听
    if (listen(server_fd, 5) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    printf("Server listening on port %d...\n", PORT);

    // 主循环接受连接
    while(1) {
        // 5. 接受新连接
        struct sockaddr_in client_addr;
        int addrlen = sizeof(client_addr);
        if ((new_socket = accept(server_fd, (struct sockaddr *)&client_addr, 
                                (socklen_t*)&addrlen)) < 0) {
            perror("accept");
            continue;  // 继续接受其他连接
        }

        // 创建线程参数
        struct thread_args *args = malloc(sizeof(struct thread_args));
        if (!args) {
            perror("malloc failed");
            close(new_socket);
            continue;
        }
        args->client_socket = new_socket;
        args->client_addr = client_addr;

        // 创建线程
        pthread_t thread_id;
        if (pthread_create(&thread_id, NULL, client_handler, (void*)args) != 0) {
            perror("pthread_create failed");
            free(args);
            close(new_socket);
            continue;
        }

        // 分离线程（自动回收资源）
        pthread_detach(thread_id);
    }

    close(server_fd);
    return 0;
}